﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace BSC_OTC_Management.Forms
{
    public partial class Form_AddNew_CongViec : Form
    {
        #region Khai báo biến
        Code.CL_Ultility _cl = new Code.CL_Ultility();
        string _ID = "";
        string _ID_ColumnName = "";
        string _formName = "";
        string _formTitle = "";
        string _function = "";
        string _thoigiandaohan = "";
        Code.StaticVariable _code = new Code.StaticVariable();
        DataTable _tableControl = new DataTable();
        DataTable _tableValue = new DataTable();
        #endregion

        public Form_AddNew_CongViec()
        {
            InitializeComponent();
        }

        public Form_AddNew_CongViec(string formName, string formTitle, string funtion, string _ID, string _ID_ColumnName)
        {
            InitializeComponent();
            this._formTitle = formTitle;
            this._formName = formName;
            this._function = funtion;
            this.Text = _formTitle;
            this._tableControl = _code._services.GetFldMasterBy_Objname(_formName);
            if (_ID != "")
            {
                this._ID = _ID;
            }
            if (_ID_ColumnName != "")
            {
                this._ID_ColumnName = _ID_ColumnName;
            }
            ShowCombobox(cbb_loaicv, formName, "LOAICV");
            ShowCombobox(cbb_trangthai, formName, "TRANGTHAI");
            
        }

        public void ShowCombobox(ComboBox cbb, string _cdtype, string _cdname){
            try
            {
                String sql = "SELECT CDVAL VALUECD, CDVAL VALUE, CDCONTENT DISPLAY FROM ALLCODE WHERE CDTYPE = '" + _cdtype + "' AND CDNAME = '" + _cdname + "' and cduser='Y' ORDER BY lstodr";

                DataTable table = new DataTable("combobox");
                table = _cl._services.GetDatatable_BySQL(sql);

                if (table.Rows.Count > 0)
                {
                    Dictionary<string, string> obj = new Dictionary<string, string>();
                    foreach (DataRow row in table.Rows)
                    {
                        obj.Add(row["VALUE"].ToString(), row["DISPLAY"].ToString());
                    }
                    cbb.DataSource = new BindingSource(obj, null);
                    cbb.DisplayMember = "Value";
                    cbb.ValueMember = "Key";
                    cbb.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }

        private bool Check_Null()
        {
            if (txt_matp.Text.Length == 0 || txt_chitietcv.Text.Length == 0)
            {
                MessageBox.Show("Không được để trống dữ liệu!");
                return false;
            }
            return true;
        }

        public string DataTableToString(DataTable dt)
        {
            string _str = "";
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                    _str += dt.Rows[0][i].ToString() + ".";

                _str = _str.Substring(0, _str.Length - 1);
            }

            return _str;
        }

        #region event
        private void btnFunction_Click(object sender, EventArgs e)
        {
            try
            {
                if (this._function == Code.StaticVariable.function_AddNew)
                {
                    _tableValue = new DataTable("_tableValue");

                    foreach (DataRow _row in this._tableControl.Rows)
                    {
                        this._tableValue.Columns.Add(_row["fldname"].ToString());
                    }

                    if (!Check_Null())
                        return;
                    string selectedLOAICV = ((KeyValuePair<string, string>)cbb_loaicv.SelectedItem).Key;
                    string selectedTRANGTHAI = ((KeyValuePair<string, string>)cbb_trangthai.SelectedItem).Key;
                    _tableValue.Rows.Add(txt_matp.Name,txt_sohd.Name, selectedLOAICV, txt_chitietcv.Text,
                        DateTime.ParseExact(dtp_thoigiancanhbao.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy"),
                        DateTime.ParseExact(dtp_thoigianthuchien.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy"), 
                        selectedTRANGTHAI);

                    // T?o xong row chưa d? li?u, t?o thêm 1 row ch?a ki?u d? li?u
                    DataRow rowDataType = _tableValue.NewRow();
                    int stt = 0;
                    foreach (DataRow _row in this._tableControl.Rows)
                    {
                        rowDataType[stt] = _row["fldtype"].ToString();
                        stt++;
                    }
                    //add data of duyet
                    this._tableValue.Rows.Add(rowDataType);
                    //string message box
                    string msg = "";

                    //lấy ngày đáo hạn để xem công việc có cần repeat ko?
                    DateTime ngaydh = Convert.ToDateTime(_thoigiandaohan);
                    if (cb_repeat.Checked)
                    {
                        for (DateTime dt = dtp_thoigianthuchien.Value.Date; dt <= ngaydh; dt = dt.AddYears(1))
                        {
                            msg = _code._services.AddNewRow_ReturnID(this._formName, this._tableValue);
                            if (_cl.IsNumeric(msg))
                            {
                                int id = Convert.ToInt32(msg);
                                //lưu vết giao dịch
                                _code._services.WritetoTLLOG(Code.StaticVariable.userID,
                                                                "",
                                                                Code.StaticVariable.menu_Code,
                                                                _cl.Current_DATE("dd/MM/yyyy"),
                                                                "",
                                                                _cl.Current_DATE("hh:mm:ss"),
                                                                "",
                                                                (int)Code.StaticVariable.approveCase.ChuaDuyet + "",
                                                                this._function,
                                                                msg,
                                                                DataTableToString(_tableValue));
                                //luu vet nguoi thuc hien
                                _code._services.Update_Last_Change(_formName, msg, Code.StaticVariable.userID);

                                //replace value tgthuchien va tgcanhbao
                                this._tableValue.Rows[0]["TGTHUCHIEN"] = Convert.ToDateTime(this._tableValue.Rows[0]["TGTHUCHIEN"]).AddYears(1).ToShortDateString();
                                this._tableValue.Rows[0]["TGCANHBAO"] = Convert.ToDateTime(this._tableValue.Rows[0]["TGCANHBAO"]).AddYears(1).ToShortDateString();
                            }
                            else
                                throw new Exception(msg);
                            
                        }

                        MessageBox.Show(Code.StaticVariable.messeseboxThemmoiThanhCong, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OK);
                        this.Close();
                    }
                    else{
                        msg = _code._services.AddNewRow_ReturnID(this._formName, this._tableValue);
                        if (_cl.IsNumeric(msg))
                        {
                            int id = Convert.ToInt32(msg);
                            //lưu vết giao dịch
                            _code._services.WritetoTLLOG(Code.StaticVariable.userID,
                                                            "",
                                                            Code.StaticVariable.menu_Code,
                                                            _cl.Current_DATE("dd/MM/yyyy"),
                                                            "",
                                                            _cl.Current_DATE("hh:mm:ss"),
                                                            "",
                                                            (int)Code.StaticVariable.approveCase.ChuaDuyet + "",
                                                            this._function,
                                                            msg,
                                                            DataTableToString(_tableValue));
                            //luu vet nguoi thuc hien
                            _code._services.Update_Last_Change(_formName, msg, Code.StaticVariable.userID);
                            MessageBox.Show(Code.StaticVariable.messeseboxThemmoiThanhCong, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OK);
                            this.Close();
                        }
                        else
                            throw new Exception(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                _tableValue = new DataTable("_tableValue");
                MessageBox.Show(ex.Message,Code.StaticVariable.messeseboxLuuY);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txt_matp_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                try
                {
                    //chuy?n sang Form View đ? t?m ki?m S? trái ch?
                    Forms.FrmView _FrmView = new Forms.FrmView("BSC_TBL_TPPH", "Quản lý trái phiếu phát hành", true);
                    _FrmView.ShowDialog();
                    //l?y v? d? li?u DataTable formView Sotraichu
                    DataTable dt = Code.StaticVariable._tbl;
                    String matp ="",tentp ="",sohd = "", tenhd = "";
                    if (dt.Columns.Count >= 5 && dt.Rows.Count >= 1)
                    {
                        matp = dt.Rows[0]["matp"].ToString();
                        tentp = dt.Rows[0]["tentp"].ToString();
                        sohd = dt.Rows[0]["sohd"].ToString();
                        tenhd = dt.Rows[0]["tenhd"].ToString();
                        this._thoigiandaohan = dt.Rows[0]["ngaydh"].ToString();
                        txt_sohd.Text = tenhd; //hthị tên Hd
                        txt_sohd.Name = sohd; //giá trị là sohd
                        txt_matp.Text = tentp;
                        txt_matp.Name = matp;
                    }
                    Code.StaticVariable._tbl.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        #endregion event
    }
}
